<?php

	class searchPager {

		private	$_array			=	array();
		private	$_result			=	null;

		private	$_startTable	=	'<table%s><tr>';
		private	$_startTag		=	'<td>';
		private	$_endTable		=	'</tr></table>';
		private	$_endTag			=	'</td>';
		private	$maxPages		=	8;
		private	$currentPage	=	1;

		public	$classTable		=	'google-pager';
		public	$idTable			=	'googlePager';
		public	$searchUrl		=	NULL;

		public function __construct($_res=NULL){

			if($_res === NULL) throw new Exception("Result must NOT be NULL");
			$this->_result	=	$_res;

		}


		public function setCurrentPage($page=1) {

			$this->currentPage	=	(!(int)$page) ? 1 : $page;

		}


		public function setMaxPages($pages=0){

			if (!(int)$pages) return;

			return $this->maxPages	=	$pages;

		}



		public function getPager(){

			$_pages		=	$this->_result->responseData->cursor->pages;
			$_current	=	$this->_result->responseData->cursor->currentPageIndex;

			foreach($_pages as $_page){

				if(($_current*8) != $_page->start){

					$url	=	sprintf($this->searchUrl,$_page->start);
					$page	=	"<a href=\"$url\">{$_page->label}</a>";

				} else
					$page	=	"{$_page->label}";

				array_push($this->_array,$page);

			}

			return $this->_array;

		}



		public function display(){

			$this->getPager();

			if (is_null($this->searchUrl)||empty($this->searchUrl)) throw (new Exception ('Search URL cannot be null, set it with setSearchUrl'));

			$class	=	($this->classTable) ? " class=\"{$this->classTable}\"" : '';
			$id		=	($this->idTable) ? " id=\"{$this->idTable}\"" : '';
			$_table	=	sprintf($this->_startTable,"{$id}{$class}");

			foreach($this->_array as $idx => $_page){

				if($idx > (int)$this->maxPages) break;
				$_table	.=	"{$this->_startTag}{$_page}{$this->_endTag}";

			}

			$_table	.=	"{$this->_endTable}";
			return $_table;

		}

		public function setFormat($format=NULL){

			switch($format){

				case 'list':
					$this->_startTable	=	'<ul%s>';
					$this->_startTag	=	'<li>';
					$this->_endTable	=	'</ul>';
					$this->_endTag	=	'</li>';
					break;

				case 'table':
				default:
					$this->_startTable	=	'<table%s><tr>';
					$this->_startTag	=	'<td>';
					$this->_endTable	=	'</tr></table>';
					$this->_endTag	=	'</td>';
					break;			

			}

		}


		public function setPage($url){

			$this->searchUrl	=	$url;

		}

		public function asArray(){
			return $this->_array;
		}

	}

?>
